<template>
  <section>
    <!-- 面包屑 -->
     <breadcrumbs></breadcrumbs>
    <!-- 查询条件 -->
    <el-form ref="searchForm" :model="searchForm" label-width="100px" inline class="demo-form-inline" size="small" style="border-bottom: 1px solid #f6f6f6">
      <el-form-item label="生效时间" prop="date">
        <el-date-picker v-model="searchForm.date" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="keyword">
        <el-input v-model="searchForm.keyword" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="
            searchForm.current = 1;
            search();
          ">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    <btns @exec="exec"></btns>
    <div class="data-container scroll-table">
      <div>
        <div class="ind-title lh50 f16">列表</div>
      </div>
      <el-table :data="tableData" style="width: 100%" ref="multipleTable" @selection-change="tableSelectionChange" row-key="ifId" border lazy
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column type="selection" width="80"> </el-table-column>
        <!-- <el-table-column prop="wxUserId" label="名师id" width="160">
        </el-table-column> -->
        <el-table-column prop="nickname" label="申请人昵称"> </el-table-column>
        <el-table-column prop="level" label="学段" width="100">
        </el-table-column>
        <el-table-column prop="org" label="机构" width="150"> </el-table-column>
        <el-table-column prop="title" label="标签">
          <template slot-scope="scope">
            <el-tag type="success" v-if="tag!=''" :key="tag" v-for="tag in scope.row.title.split(',')">{{tag}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.enable == 1">启用</span>
            <span v-if="scope.row.enable == 2">禁用</span>
          </template>
        </el-table-column>

        <el-table-column prop="checktime" label="生效时间"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <div>
              <el-button size="small" type="primary" @click="toDetail(scope.row)">详情</el-button>
              <el-button size="small" type="primary" @click="toTag(scope.row)">修改标签</el-button>
              <el-button size="small" type="primary" @click="toFerrerDialog(scope.row)">推荐值</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!--新增修改界面-->
    <el-dialog :title="funTit == 'add' ? '新增' : '修改'" :visible.sync="addORUpdateVisible" width="700px" :before-close='clearUpdate'
               :close-on-click-modal="false">
      <el-form :model="userForm" label-width="120px" :rules="userFormRules" ref="userForm">
        <el-form-item label="名师名称" prop="name">
          <el-input v-model="userForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="名师头像" prop="headImg">
          <el-upload :action="uploadFile" list-type="picture-card" :on-remove="handleRemove" :on-success="handleAvatarSuccess" v-model="userForm.headImg"
                     :limit="1" :file-list="filesEdit">
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">只能上传1图片</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="学段" prop="level">
          <el-input v-model="userForm.level" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="机构" prop="org">
          <el-input v-model="userForm.org" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="ds">
          <Editor ref="child" v-model="userForm.ds"></Editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="clearUpdate()">取消</el-button>
        <el-button type="primary" v-if="funTit!='detail'" @click.native="submit('userForm')">提交</el-button>
      </div>
    </el-dialog>
    <!--设置推荐值-->
    <el-dialog title="设置推荐值" :visible.sync="setFerrerDialog">
      <el-form :model="addForm" ref="addForm" :rules="addForRules">
        <el-form-item label="推荐值" :label-width="formLabelWidth" prop="title">
          <el-input v-model="addForm.isReferrer" type="number" min='0' autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearAdd">取 消</el-button>
        <el-button type="primary" @click="addFerrer('addForm')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<style>
</style>
<script>
import mixins from "@/utils/mixins";
import btns from "@/components/btns.vue";
import breadcrumbs from "@/components/breadcrumbs.vue";
import Editor from '../../components/edit.vue'
export default {
  mixins: [mixins],
  components: {
    btns,
    breadcrumbs,
    Editor,
  },
  data() {
    return {
      userForm: {},
      userFormRules: {
        name: [
          { required: true, message: "请输入名师名称", trigger: "change" },
        ],
        level: [
          { required: true, message: "请输入学段", trigger: "blur" },
        ],
        org: [
          { required: true, message: "请输入机构", trigger: "blur" },
        ],
        ds: [
          { required: true, message: "请填写介绍", trigger: "blur" },
        ],
        headImg: [
          {
            required: true, message: '请上传名师头像', trigger: 'change'
          }
        ],
      },
      funTit: 'add',
      uploadFile: this.GLOBAL.imgBaseUrl,
      filesEdit: [],
      changeHeadImgform: {},
      addORUpdateVisible: false,
      setFerrerDialog: false,
      addForm: {},
      addForRules: {
        "isReferrer": [{
          required: true,
          message: '请输入推荐值',
          trigger: 'blur'
        }],
      },
      formLabelWidth: '120px',
      searchForm: {
        date: [],
        title: "",
        endTime: "",
        beginTime: "",
        current: 1,
        size: 10,
        totalCount: "",
        keyword: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,

    };
  },
  created() {
    this.orderList(this.currentPage, this.pageSize);
  },
  methods: {
    handleRemove(file, fileList) {
      this.userForm.headImg = '';
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file);
      this.userForm.headImg = res.replace(this.previewPicture, '');
      // this.$set(this.userForm.headImg, res.replace(this.previewPicture, ''))

    },
    tableSelectionChange(val) {
      this.tableSelection = val;
    },
    exec(fun) {
      if (this[fun]) {
        this.funTit = fun;
        this[fun]();
      } else {
        this.$message.error("方法未定义");
      }
    },
    toTag(row) {
      this.$router.push({
        path: `/teacher/teacherType`,
        query: { id: row.wxUserId },
      });
    },
    clearAdd() {
      this.setFerrerDialog = false;
      this.addForm = {};
    },
    toFerrerDialog(row) {
      this.setFerrerDialog = true;
      this.rowUserid = row.wxUserId
    },
    addFerrer(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$api.teacher
            .setTeacherFerrer({
              isReferrer: this.addForm.isReferrer,
              userId: this.rowUserid,
            })
            .then((d) => {
              if (d.code == 200) {
                this.setFerrerDialog = false;
                this.$refs[formName].resetFields();
                this.$message.success('设置成功！');
              } else {
                this.$message.error(d.msg);
              }
            })
            .catch((e) => {
              console.log(e);
            });
        }
      })
    },
    toFerrer(row) {

      this.$router.push({
        path: `/teacher/setTeacherFerrer`,
        query: { id: row.wxUserId },
      });
    },
    search() {
      this.orderList(this.currentPage, this.pageSize);
    },
    orderList(cur, ss) {
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        this.searchForm.beginTime = this.format(this.searchForm.date[0]);
        this.searchForm.endTime = this.format(this.searchForm.date[1]);
      }
      this.$api.teacher
        .getTeacherList({
          current: cur,
          size: ss,
          beginTime: this.searchForm.beginTime,
          endTime: this.searchForm.endTime,
          keyword: this.searchForm.keyword,
        })
        .then((d) => {
          this.tableData = d.data;
          this.total = d.totalCount;
        })
        .catch((e) => {
          console.log(e);
        });
    },
    toDetail(row) {
      this.tableSelection = [row]
      this.update()
      this.funTit = 'detail'
    },
    clearUpdate() {
      if (this.$refs.hasOwnProperty("userForm")) {
        this.$refs['userForm'].resetFields();
      }
      this.userForm = {}
      this.addORUpdateVisible = false;
      this.filesEdit = [];
      this.$refs.child.clearText();
      this.tableSelection = [];
      this.$refs.multipleTable.clearSelection();
    },
    update() {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.userForm.name = this.tableSelection[0].nickname;
      this.userForm.level = this.tableSelection[0].level;
      this.userForm.org = this.tableSelection[0].org;
      this.userForm.ds = this.tableSelection[0].ds;
      this.userForm.headImg = this.uploadFile + this.tableSelection[0].headUrl;
      let file = this.tableSelection[0].headUrl.split(",");
      file.forEach((item, index) => {
        if (item != "") {
          this.filesEdit.push({
            url: item,
            index: index
          })
        }
      });
      this.addORUpdateVisible = true;
      this.funTit = 'update'
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            name: this.userForm.name,
            level: this.userForm.level,
            org: this.userForm.org,
            ds: this.userForm.ds,
            headImg: this.userForm.headImg,
            userId: this.tableSelection[0].wxUserId,
          }
          if (this.funTit == 'add') {
          } else {
            this.$api.teacher
              .editTeacher(params)
              .then((d) => {
                if (d.code == 200) {
                  this.clearUpdate();
                  this.$message.success('操作成功！');
                } else {
                  this.$message.error(d.msg);
                }
              })
              .catch((e) => {
                console.log(e);
              });
          }
        }
      })
    },
    //启用
    enable() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选择要操作的数据！");
        return;
      }
      let ids = this.tableSelection.map((e) => {
        return e.enable;
      });
      let wxUserIds = this.tableSelection.map((e) => {
        return e.wxUserId;
      });
      let s = new Set(ids);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] != 2) {
        return this.$message.error("请选择状态为禁用数据！");
      }
      this.$confirm("确认要启用这个名师, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.teacher
            .enableTeacher({
              userIds: wxUserIds.join(","),
              state: 1, //状态 2禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "启用成功",
                });
                this.orderList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消启用");
        });
    },
    //禁用
    disable() {
      if (this.tableSelection.length < 1) {
        this.$message.error("请选择要操作的数据！");
        return;
      }
      let ids = this.tableSelection.map((e) => {
        return e.enable;
      });
      let wxUserIds = this.tableSelection.map((e) => {
        return e.wxUserId;
      });
      let s = new Set(ids);
      if ([...s].length != 1) {
        return this.$message.error("请选择状态一致的数据！");
      }
      if ([...s][0] != 1) {
        return this.$message.error("请选择状态为启用数据！");
      }
      this.$confirm("确认要禁用这个名师, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.teacher
            .enableTeacher({
              userIds: wxUserIds.join(","),
              state: 2, //状态 2禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "禁用成功",
                });
                this.orderList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消禁用");
        });
    },
    handleReset() {
      this.searchForm = {
        keyword: "",
      };
      (this.endTimee = ""), (this.beginTimee = ""), this.search();
    },
    handleSizeChange(v) {
      console.log(v)
      this.searchForm.size = v;
      this.orderList(this.searchForm.current, v);
    },
    handleCurrentChange(v) {
      this.searchForm.current = v;
      this.orderList(v, this.searchForm.size, v);
    },
  },
};
</script>
<style scoped>
.dialog-footer {
  margin-top: 50px;
}
.top-box {
  width: 100%;

  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 80px;
}

.top-item {
  border: 1px rgb(189, 185, 185) solid;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  margin-right: 100px;
}
.top-icon {
  width: 30%;
  height: 30%;
  margin-right: 30px;
  margin-left: 30px;
}
.fontText {
  font-size: 20px;
}

.fontTop {
  font-size: 40px;
}
.f18 {
  font-size: 25px;
  font-weight: 700;
}
.mgb-20 {
  font-size: 16px;
}
</style>
